package xx.iverson.navigation_manager.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import xx.iverson.navigation_manager.entity.SysUser;
import xx.iverson.navigation_manager.mapper.SysUserMapper;
import xx.iverson.navigation_manager.service.UserService;

/**
 * xx.iverson.navigation_manager.service.impl.UserServiceImpl
 * 描述：
 * on 2025/9/26-下午2:32
 *
 * @author weijx
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private SysUserMapper userMapper;

    @Override
    public SysUser findByUsername(String username) {
        return userMapper.findByUsername(username);
    }

    @Override
    public SysUser findById(Integer id) {
        return userMapper.findById(id);
    }

    @Override
    public boolean register(SysUser user) {
        // 检查用户名是否已存在
        if (userMapper.findByUsername(user.getUsername()) != null) {
            return false;
        }

        // 对密码进行MD5加密
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        return userMapper.insert(user) > 0;
    }

    @Override
    public boolean updatePassword(Integer id, String newPassword) {
        String encryptedPassword = DigestUtils.md5DigestAsHex(newPassword.getBytes());
        return userMapper.updatePassword(id, encryptedPassword) > 0;
    }

    @Override
    public boolean updateUser(SysUser user) {
        // 如果密码不为空，则加密密码
        if (user.getPassword() != null && !user.getPassword().isEmpty()) {
            user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        }
        return userMapper.update(user) > 0;
    }
}
